package com.example.actionhandlers.actions;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.SystemClock;
import android.view.KeyEvent;

import com.example.actionhandlers.AbstractAction;
import com.example.singletones.contextObj;

public class MediaPlayAction extends AbstractAction {

	public boolean isApplicable(JSONObject jsonObj) {
		try {
			return jsonObj.has("actionName")
					&& jsonObj.getString("actionName")
							.equalsIgnoreCase("media");
		} catch (JSONException e) {
			return false;
		}
	}

	public void performAction(JSONObject jsonObj) throws Exception {
		AudioManager mAudioManager = (AudioManager) contextObj.getInstance()
				.getmContext().getSystemService(Context.AUDIO_SERVICE);

		if (!mAudioManager.isMusicActive()) {
			long eventtime = SystemClock.uptimeMillis();

			Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
			KeyEvent downEvent = new KeyEvent(eventtime, eventtime,
					KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY, 0);
			downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
			contextObj.getInstance().getmContext()
					.sendOrderedBroadcast(downIntent, null);
		}
	}

	public String getActionName() {
		return "media";
	}
}
